package com.qianfeng.zhangwei.xmppdemo.connection;

import android.os.Build;
import android.os.Handler;
import android.os.Message;

import com.qianfeng.zhangwei.xmppdemo.config.XmppConfig;

import org.jivesoftware.smack.AccountManager;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.muc.MultiUserChat;


/**
 * @说 明：
 * @项目名称：Sz1504Adv
 * @包 名： com.qianfeng.zhangwei.xmppdemo.connection
 * @类 名： XmppHelper
 * @创 建人： zhangwei
 * @创建时间：2015-08-11 14:41
 * @版 本：v1.0
 * @修 改人：
 * @修改时间：
 * @修改备注：
 */
public class XmppHelper {
    private static XmppHelper helper;

    private static XMPPConnection connection;
    private static boolean isConnection = false;


    private static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    isConnection = true;
                    //连接服务器成功
                    break;
                case 2:
                    isConnection = false;
                    //连接服务器失败
                    break;
            }

        }
    };

    private XmppHelper() {
        getXmppConnection();
    }

    public static XmppHelper getInstance() {
        if (helper == null) {
            helper = new XmppHelper();
        }
        return helper;
    }

    /**
     * 1表示成功
     * 2表示连接服务器失败
     */
    public void init() {
        if (getXmppConnection() != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int state;
                    try {
                        getXmppConnection().connect();
//                        createUser("sz1504","123456");
                        login("sz1504","123456");
                        chat();
                        state = 1;
                    } catch (XMPPException e) {
                        e.printStackTrace();
                        state = 2;
                    }
                    handler.sendEmptyMessage(state);
                }
            }).start();

        }
    }


    /**
     * 获取xmpp核心连接类
     *
     * @return
     */
    public XMPPConnection getXmppConnection() {
        if (connection == null) {
            //用android基础
            connection = new XMPPConnection(getConnectionConfiguration());
        }
        return connection;
    }


    /**
     * 获取xmpp连接配置类
     *
     * @return
     */
    public ConnectionConfiguration getConnectionConfiguration() {

        /**
         * 初始化连接配置类
         */
        ConnectionConfiguration configuration = new ConnectionConfiguration(XmppConfig.SERVER_HOST, XmppConfig.SERVER_PORT, XmppConfig.CLIENT_NAME);

        configuration.setDebuggerEnabled(true);
        //允许断线重连
        configuration.setReconnectionAllowed(true);
        //不启用sasl安全协议
        configuration.setSASLAuthenticationEnabled(false);
        //接受离线消息
        configuration.setSendPresence(true);
        ///tls
        configuration.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
        //4.0以后
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            configuration.setTruststoreType("AndroidCAStore");
            configuration.setTruststorePath(null);
            configuration.setTruststorePassword(null);
        } else {
            configuration.setTruststoreType(XmppConfig.TRUST_STORE_TYPE);
            String caPath = XmppConfig.TRUST_PROPERTY_PATH;
            if (caPath != null) {
                caPath = XmppConfig.TRUST_STORE_PATH;
            }
            configuration.setTruststorePath(caPath);
        }
        return configuration;
    }

    public void login(String userName, String passWord) {
//        AccountManager manager = xmppConnection.getAccountManager();
        try {
            getXmppConnection().login(userName, passWord);
        } catch (XMPPException e) {
            e.printStackTrace();
        }
    }

    /**
     * sate 1表示成功
     *
     * @param user
     * @param psw
     * @return
     */
    private int createUser(String user, String psw) {
        int state;
        AccountManager manager = getXmppConnection().getAccountManager();
        state = 1;
        try {
            manager.createAccount(user, psw);
        } catch (XMPPException e) {
            e.printStackTrace();
            state = 2;
        }
        return state;
    }

    private void chat() {
        ChatManager chatManager = getXmppConnection().getChatManager();
        chatManager.addChatListener(new ChatManagerListener() {
            @Override
            public void chatCreated(Chat chat, boolean createdLocally) {
                chat.addMessageListener(new MessageListener() {
                    @Override
                    public void processMessage(Chat chat, org.jivesoftware.smack.packet.Message message) {
                        message.getBody();
                    }
                });
            }
        });

    }

    /**
     *
     */
    public void moreChats() {
        MultiUserChat multiUserChat = new MultiUserChat(getXmppConnection() , "1504");

        multiUserChat.addMessageListener(new PacketListener() {
            @Override
            public void processPacket(Packet packet) {
                String msg = packet.getFrom();
            }
        });
    }

}
